package com.microservices.cloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.microservices.cloud.entities.CommonResult;
import com.microservices.cloud.entities.Payment;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@Slf4j
public class CircleBreakerController {


    @Resource
    private RestTemplate restTemplate;

    @Value("${service-url.nacos-user-service}")
    private String serverURL;


    @GetMapping(value = "/consumer/fallback/{id}")
//    @SentinelResource(value = "fallback")  //没有配置
//    @SentinelResource(value = "fallback", fallback = "handlerFallback") //fallback 只负责业务异常
//    @SentinelResource(value = "fallback", blockHandler = "blockHandler") //blockHandler 只负责sentinel控制台配置违规
    @SentinelResource(value = "fallback", blockHandler = "blockHandler", fallback = "handlerFallback", exceptionsToIgnore = {IllegalArgumentException.class})
    //自己负责处理自己的那一块
    public CommonResult<Payment> fallback(@PathVariable("id") Long id) {
        CommonResult<Payment> payment = restTemplate.getForObject(serverURL + "/payment/nacos/" + id, CommonResult.class);
        if (id == 4) {
            throw new IllegalArgumentException("IllegalArgumentException,非法参数异常");
        } else if (payment.getData() == null) {
            throw new NullPointerException("NullPointerException,该ID没有对应的记录，空指针异常");
        }
        return payment;
    }

    public CommonResult<Payment> handlerFallback(@PathVariable("id") Long id, Throwable throwable) {
        Payment payment = new Payment(id, "null");
        return new CommonResult<>(444, "兜底异常handlerFallback，exception 内容 " + throwable.getMessage(), payment);
    }


    public CommonResult<Payment> blockHandler(@PathVariable("id") Long id, BlockException blockException) {
        Payment payment = new Payment(id, "null");
        return new CommonResult<>(445, "blockHandler-sentinel 限流，无此流水" + blockException.getMessage(), payment);
    }




}
